var host = window.location.protocol + "//" + window.location.hostname + "/";
var globalconfig = {'loadindexadrr':host+'index.php?m=content&c=index&a=ajax_init&',
    'savecommaddr':host+'index.php?m=comment&c=index&a=ajax_save&',
    'checkcodeaddr':host+'api.php','loginaddr':host+'index.php?m=admin&c=login&a=userlogin&',
    'getcategoryaddr':host+'index.php?m=navigation&c=index&a=ajax_init&',
    'editorconfigaddr':host+'statics/js/ueditor/ueditor.config.js',
    'editoraddr':host+'statics/js/ueditor/ueditor.all.min.js',
    'savearticleaddr':host+'index.php?m=content&c=content&a=save&',
    'userregistraddr':host+'index.php?m=admin&c=index&a=register&'
    };
$(document).ready(function() {
    var checkP = false;
    var checkU = false;
    var regpasswd = false;
    var nicknamebool = false;
    var webbool = true;
    var commbool = false;
    window.commId = 0;
    window.UEDITOR_HOME_URL =host+'statics/js/ueditor/';
    console.info( window.UEDITOR_HOME_URL);
    jQuery.extend({
        checkmail: function(val) {
            var exp = new RegExp("^([a-z0-9_.-]+)@([\da-z.-\d]+).([a-z.]{2,6})$", "i");
            return exp.test(val)
        },
        checkUsername: function(val) {
            var exp = new RegExp("^[a-z0-9A-Z]{2,100}$");
            return exp.test(val)
        },
        checkpass: function(val) {
            var exp = new RegExp("^[a-z0-9_-]{6,100}$", "i");
            return exp.test(val)
        },
        checkcaptcha: function(val) {
            var exp = new RegExp("^[a-z0-9]{4}$", "i");
            return exp.test(val)
        },
        checkWeb: function(val) {
            var exp = new RegExp("^[a-z]+\.([a-z0-9]+)\.([a-z\.]{2,6})$", "i");
            return exp.test(val)
        },
        switchClass: function(_this, bool) {
            if (!bool) {
                $(_this).addClass("error")
            } else {
                $(_this).removeClass("error")
            }
        },
        intval: function(_this, string) {
            var str = string;
            if ($(_this).val() == str) {
                $(_this).val("");
                $(_this).removeClass()
            }
            $(_this).focusout(function() {
                if (!$(_this).val()) {
                    $(_this).val(str);
                    $(_this).addClass("input_color")
                }
            })
        },
        errorTip: function(_this, bool) {
            if (!bool) {
                $(_this).addClass("error")
            }
        },
        removeError: function(_this) {
            if (!_this) {
                var _this = $('a[name="closeButton"]')
            }
            $(_this).parent().remove()
        },
        throwError: function(str, color) {
            if ($("#error").length == 0) {
                var colorArr = ["rgba(255, 6, 6, 0.63)", "rgba(241, 194, 6, 0.57)", "rgba(81, 241, 6, 0.57)"];
                $("body").prepend('<div id="error"  style="position:fixed;left:0;top:60px;height:30px;background:#FBEA9E;color:#080808;z-index:100000;width:100%;text-align:center;font-size:16px;line-height:30px;box-shadow:5px 5px 5px ' + colorArr[color] + ';">' + str + ' <a style="float:right;margin-right:30px;font-size:16px;color:red;cursor:default;height:10px;width:10px;hover:green;" onclick="jQuery.removeError(this)" name="closeButton">x</a></div>')
            }
        },
        autoCloseError: function(str, type, time, color) {
            if (!type) {
                jQuery.throwError(str, color);
                return false
            }
            if (type == 1) {
                jQuery.throwError(str, color);
                window.setTimeout("jQuery.removeError()", time);
                return false
            }
        },
        closeEdit: function(_this) {
            $("#editarticle").remove()
        },
        getHostName: function() {
            var hostname = location.hostname;
            return hostname
        },
        startajax: function(str) {
            var string = str;
            $(document).ajaxStart(function() {
                jQuery.autoCloseError(string, 1, 700, 2)
            })
        },
        userRegLogin: function(_this) {

            switch ($(_this).val()) {
            case "登陆":
                var serialize = $("#loginReg").serialize();
                jQuery.startajax("正在登陆....");
                console.info(serialize);
                $.post(globalconfig.loginaddr,serialize,
                function(data) {
                    if (eval(data) != "true") {
                        jQuery.removeError();
                        jQuery.autoCloseError(eval(data), 1, 700, 2)
                    }
                    if (eval(data) == "true") {
                        window.location.reload()
                    }
                },
                "json");
                break;
            case "注册":
                var serialize = $("#loginReg").serialize();
                jQuery.startajax("正在注册.....");
                $.post(globalconfig.userregistraddr, serialize,
                function(data) {
                    var error = eval(data);
                    if (error['login'] == true) {
                        window.location.reload();
                        return '';
                    }
                    jQuery.removeError();
                    jQuery.autoCloseError(error, 1, 700, 2);


                },
                "json");
                break
            }
        },
        removeLoginbox: function() {
            var from = $("#login");
            from.remove();
            $(".nav_login").addClass("nav_logined");
            $(".nav_login").attr("style", "margin-top:4px;")
        },
        getCookie: function(key) {
            if (document.cookie.length > 0) {
                start = document.cookie.indexOf(key + "=");
                if (start != -1) {
                    start = start + key.length + 1;
                    end = document.cookie.indexOf(";", start);
                    if (end == -1) {
                        end = document.cookie.length
                    }
                    return unescape(document.cookie.substring(start, end))
                }
            }
            return ""
        },
        openRegBox: function() {
            $("#loginbox").slideDown("slow")
        },
        swreglog: function() {
            $('a[title="关闭"]').siblings().each(function() {
                $(this).click(function() {
                    if ($(this).attr("class") != "regselected") {
                        $(this).addClass("regselected");
                        $(this).siblings().removeClass("regselected");
                        $(this).siblings().addClass("regselect");
                        $("#button").val($(this).attr("title"))
                    }
                })
            })
        },
        closeRegBox: function(_this) {
            $(_this).parent().parent().parent().slideUp("slow",
            function() {
                $(_this).parent().parent().parent().remove()
            })
        },
        switchCaptcha: function(_this) {
            $(_this).attr("src", globalconfig.checkcodeaddr+'?'+ Math.random())
        },
        loadEditor: function() {
            jQuery.startajax("正在加载");
            $.post(globalconfig.getcategoryaddr,
            function(data, jqxhr) {
                window.string = "";
                var cate = eval(data);
                for (var i = 0; i < cate.length; i++) {
                    window.string += '<option value="' + cate[i].id + '">' + cate[i].name + "</option>"
                }
                var a = $.getScript(globalconfig.editorconfigaddr,
                function(data, textStatus, jqxhr) {
                    $.getScript(globalconfig.editoraddr,
                    function() {
                        var top = $(window).scrollTop() + ($(window).height() / 6);
                        var margin = ($(window).width()-1024)/2;
                        $('#editarticle').css({left:margin});
                        var editor = '<div class="edit" id="editarticle" style="position:absolute;top:' + top + 'px;left: 12%;z-index: 1000;"><p><label>标题:</label><input type="text" name="title" id="arttitle"/><span>分类：</span><span><select id="categroy"><option>请选择</option>' + window.string + '</select></span><span class="edit_tool"><a href="javascript:void(0)" onclick="jQuery.closeEdit(this,event)">关闭</a></span></p><script id="editor" type="text/plain" style="width:1024px;height:400px;">' + "<\/script>" + '<p class="editTag"><label>标签(用逗号隔开):</label><input type="text" name="tag" id="tagname"/><span><a href="javascript:void(0)" id="leave">发表</a></span></p></div>';
                        $("body").append(editor);
                        UE.getEditor("editor");
                        $("#leave").click(function() {
                            jQuery.leaveGetval()
                        })
                    }).fail(function(jqxhr) {
                        jQuery.throwError("文章编辑器ueditor载入错误：代码" + jqxhr.status, 0)
                    })
                }).fail(function(jqxhr) {
                    jQuery.throwError("文章编辑器config载入错误：代码" + jqxhr.status, 0)
                })
            },
            "json")
        },
        leaveGetval: function() {
            var tagname = $("#tagname").val();
            var arttitle = $("#arttitle").val();
            var categroy = $("#categroy option:selected").val();
            if (!arttitle) {
                jQuery.autoCloseError("请填写标题", 1, 700, 2);
                return false
            }
            if (categroy == "请选择") {
                jQuery.autoCloseError("请填选择分类", 1, 700, 2);
                return false
            }
            if (!UE.getEditor("editor").hasContents()) {
                jQuery.autoCloseError("请填写内容", 1, 700, 2);
                return false
            }
            if (!tagname) {
                jQuery.autoCloseError("请填写标签", 1, 700, 2);
                return false
            }
            var content = UE.getEditor("editor").getContent();
            content = encodeURIComponent(content);
            var article = "title=" + arttitle + "&categroy=" + categroy + "&content=" + content + "&tagname=" + tagname;
            jQuery.startajax("正在发布");
            $.ajax({
                type: "POST",
                url: globalconfig.savearticleaddr,
                data: article,
                success: function(data) {
                    console.info(data);
                    if (eval(data) != "true") {
                        jQuery.removeError();
                        jQuery.autoCloseError(eval(data), 1, 700, 2)
                    }
                    if (eval(data) == "true") {
                        window.location.reload()
                    }
                }
            })
        },
        leavecomm: function() {
            var comminfo = $("#leavecomm").serialize();
            var commcontent = encodeURIComponent($("#commcontent").val());
            var articleId = $("#articlename").attr("data-id");
            var comm = "commcontent=" + commcontent + "&" + comminfo + "&articleId=" + articleId + "&url=" + location.href + "&commId=" + commId;
            console.info(comm);
            jQuery.startajax("正在发布评论....");
            $.ajax({
                type: "POST",
                url: globalconfig.savecommaddr,
                data: comm,
                dataType: "json",
                success: function(msg) {
                    jQuery.removeError();
                    jQuery.autoCloseError(eval(msg), 1, 1000, 2);
                    window.location.reload()
                }
            })
        },
        removeLeave: function() {
            $("#comm").removeAttr("disabled", "false")
        },
        loadindex: function() {
            var articleId = $('p[class="readmore"] a').last().attr("data-id");
            var categoryid = $('p[class="readmore"] a').last().attr("data-category");
            if (ajaxLoad) {
                $(document).ajaxStart(function() {
                    $(".indexreadmore").addClass("ajaxload")
                });
                $(document).ajaxStop(function() {
                    jQuery.removeError()
                });
                $.post(globalconfig.loadindexadrr+'aid='+articleId+'&category='+categoryid,
                function(json) {
                    if (json.length != 0) {
                        var articles = eval(json);
                        $(articles).each(function() {
                            $(".artcle ul").append($(this)[0])
                        });
                        return
                    }
                    jQuery.removeError();
                    jQuery.autoCloseError("欢迎发表你的看法", 1, 1000, 2);
                    ajaxLoad = false;
                    return
                },
                "json").fail(function() {
                    jQuery.throwError("文章加载失败错误：代码" + jqxhr.status, 0)
                })
            }
        },
        checklogregbox: function() {
            $('input[name="username"]').focus(function() {
                var string = "电子邮件/Email";
                jQuery.intval($(this), string)
            });
            $('input[name="username"]').change(function() {
                var bool = jQuery.checkmail($(this).val());
                jQuery.errorTip($(this), bool);
                if (!bool) {
                    jQuery.autoCloseError("请填写正确电子邮件", 1, 1000, 2)
                } else {
                    checkU = true
                }
                if (nicknamebool && commbool && checkU) {
                    jQuery.removeLeave()
                }
            });
            $('input[name="passwd"]').change(function() {
                var bool = jQuery.checkpass($(this).val());
                if (!bool) {
                    jQuery.autoCloseError("密码不能为空，不能少于6个字符", 1, 1000, 2)
                } else {
                    checkP = true
                }
            });
            $('input[name="captcha"]').change(function() {
                var bool = jQuery.checkcaptcha($(this).val());
                if (!bool) {
                    jQuery.autoCloseError("验证码不正确", 1, 1000, 2)
                } else {
                    regpasswd = true
                }
            })
        },
        initeditor: function() {
            if (jQuery.getCookie("login") != 1) {
                var top = $(window).scrollTop() + ($(window).height() / 6);
                var margin = ($(window).width()-390)/2;
                $('#loginbox').css({left:margin});
                var loginbox = '<div id="loginbox" style="display:none;position:absolute;top:' + top + 'px;left:35%"><form id="loginReg"><p class="regstr regstrshadow" id="menu"><a href="javascript:void(0)" class="regselected" title="登陆" alt="login">登陆</a><a href="javascript:void(0)" class="regselect" title="注册" alt="register">注册</a><a href="javascript:void(0)" onclick="jQuery.closeRegBox(this)" class="regselect" title="关闭">关闭</a></p>		<p><label>电子邮件:  </label><input type="text" name="username"></p><p><label>密码:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="password" name="passwd"></p>		<p><label>验证码:</label>&nbsp;&nbsp;&nbsp;<input type="text" name="captcha"></p><p id="check"><img src="'+globalconfig.checkcodeaddr+'" width="100px" height="40px" title="看不清楚清猛点,不然会看不清楚" alt="看不清楚清猛点,不然会看不清楚" onclick="jQuery.switchCaptcha(this)"></p><p class="regbtn"><input type="button" value="登陆"  id="button" onclick="jQuery.userRegLogin(this)"></p></form>	</div>';
                if ($("#loginbox").length == 0) {
                    $("body").append(loginbox)
                }
                jQuery.openRegBox();
                jQuery.swreglog();
                jQuery.checklogregbox();
                return false
            }
            if ($(".edit").length == 0) {
                jQuery.loadEditor()
            }
        },
        qqtoLogin: function(){
           var A=window.open("api/qqlogin.php","TencentLogin", 
           "width=450,height=320,menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1");
         } 
    });
    $('input[name="email"]').focus(function() {
        var string = "电子邮件/Email";
        jQuery.intval($(this), string)
    });
    $('input[name="email"]').change(function() {
        var bool = jQuery.checkmail($(this).val());
        jQuery.errorTip($(this), bool);
        if (!bool) {
            jQuery.autoCloseError("请填写正确电子邮件", 1, 1000, 2)
        } else {
            checkU = true
        }
        if (nicknamebool && commbool && checkU) {
            jQuery.removeLeave()
        }
    });
    $("#nickname").focus(function() {
        var string = "昵称/英文和数字";
        jQuery.intval($(this), string)
    });
    $("#nickname").change(function() {
        var bool = jQuery.checkUsername($(this).val());
        jQuery.errorTip($(this), bool);
        if (!bool) {
            jQuery.autoCloseError("请正确填写昵称", 1, 1000, 2)
        } else {
            nicknamebool = true
        }
        if (nicknamebool && commbool && checkU) {
            jQuery.removeLeave()
        }
    });
    $('input[name="passwd"]').change(function() {
        var bool = jQuery.checkpass($(this).val());
        if (!bool) {
            jQuery.autoCloseError("密码不能为空，不能少于6个字符", 1, 1000, 2)
        } else {
            checkP = true
        }
    });
    $('input[name="captcha"]').change(function() {
        var bool = jQuery.checkcaptcha($(this).val());
        if (!bool) {
            jQuery.autoCloseError("验证码正确", 1, 1000, 2)
        } else {
            regpasswd = true
        }
    });
    $("#web").focus(function() {
        var string = "www.myfreax.com";
        jQuery.intval($(this), string)
    });
    $("#web").change(function() {
        var bool = jQuery.checkWeb($(this).val());
        jQuery.errorTip($(this), bool);
        if (!bool) {
            jQuery.autoCloseError("请正确个人主页", 1, 1000, 2)
        } else {
            webbool = true
        }
        if (webbool && nicknamebool && commbool && checkU) {
            jQuery.removeLeave()
        }
    });
    $("#commcontent").focus(function() {
        var string = "内容不能为空";
        jQuery.intval($(this), string)
    });
    $("#commcontent").change(function() {
        var con = $(this).val();
        if (con != "" && con != "内容不能为空") {
            var bool = true
        } else {
            var bool = false
        }
        if (!bool) {
            jQuery.autoCloseError("请正确个人主页", 1, 1000, 2)
        } else {
            commbool = true
        }
        if (nicknamebool && commbool && checkU) {
            jQuery.removeLeave()
        }
    });
    $("ul[class='tab_list'] a").mouseover(function() {
        var div_id = $(this).attr("href");
        var displayDiv = $("#" + div_id);
        $("div[name=tab]").attr("style", "display:none");
        displayDiv.show()
    });
    $.ajaxSetup({
        cache: true
    });
    $('div[class="leaveArtcile"] a').click(function(event) {
        jQuery.initeditor()
    });
    var ajaxLoad = true;
    $("#load").click(function() {
        jQuery.loadindex()
    });
    $("#userinfo").mouseover(function() {
        $(this).children().slideDown(200,
        function() {
            $(this).mouseleave(function() {
                $(this).slideUp(200)
            })
        })
    });
    $("#comm").click(function() {
        jQuery.leavecomm()
    });
    $(".call").click(function() {
        var nickname = $(this).parent().siblings();
        window.commId = $(this).attr("id");
        if (nickname[0].nodeName == "SPAN") {
            $("#commcontent").text("@" + nickname.eq(0).text() + ": ")
        }
    })
});
